package com.yidingdui.service.impl;

import com.yidingdui.domain.entity.ModelHistory;
import com.yidingdui.domain.vo.ModelHistoryVO;
import com.yidingdui.mapper.ModelHistoryMapper;
import com.yidingdui.service.ModelHistoryService;
import com.yidingdui.service.CacheService;
import com.yidingdui.util.BeanUtils;
import com.yidingdui.websocket.TaskNotificationEndpoint;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class ModelHistoryServiceImpl implements ModelHistoryService {
    
    private final ModelHistoryMapper modelHistoryMapper;
    private final CacheService cacheService;
    
    @Override
    public ModelHistory createTask(String taskId, Long userId, String prompt, String imageFileName, 
                                  Boolean enablePBR, String resultFormat) {
        ModelHistory modelHistory = ModelHistory.builder()
                .taskId(taskId)
                .userId(userId)
                .prompt(prompt)
                .imageFileName(imageFileName)
                .enablePBR(enablePBR)
                .resultFormat(resultFormat)
                .status("RUN")
                .createdAt(LocalDateTime.now())
                .updatedAt(LocalDateTime.now())
                .build();
        
        modelHistoryMapper.insertModelHistory(modelHistory);
        log.info("创建模型生成任务: taskId={}, userId={}", taskId, userId);
        return modelHistory;
    }
    
    @Override
    public void updateTaskSuccess(String taskId, String resultUrl) {
        ModelHistory modelHistory = ModelHistory.builder()
                .taskId(taskId)
                .status("DONE")
                .resultUrl(resultUrl)
                .updatedAt(LocalDateTime.now())
                .completedAt(LocalDateTime.now())
                .build();
        
        modelHistoryMapper.updateByTaskId(modelHistory);
        
        // 清除相关缓存
        ModelHistory history = modelHistoryMapper.findByTaskId(taskId);
        if (history != null) {
            cacheService.clearUserHistoryCache(history.getUserId());
            cacheService.clearTaskStatusCache(taskId);
            
            // 发布任务完成通知
            cacheService.publishTaskCompletion(taskId, "DONE", "模型生成完成");
            
            // 发送WebSocket实时通知
            TaskNotificationEndpoint.sendTaskNotification(
                history.getUserId().toString(), 
                taskId, 
                "DONE", 
                "任务已完成，模型生成成功！"
            );
        }
        
        log.info("模型生成任务完成: taskId={}, resultUrl={}", taskId, resultUrl);
    }
    
    @Override
    public void updateTaskFailure(String taskId, String errorMessage) {
        ModelHistory modelHistory = ModelHistory.builder()
                .taskId(taskId)
                .status("FAIL")
                .errorMessage(errorMessage)
                .updatedAt(LocalDateTime.now())
                .completedAt(LocalDateTime.now())
                .build();
        
        modelHistoryMapper.updateByTaskId(modelHistory);
        
        // 清除相关缓存
        ModelHistory history = modelHistoryMapper.findByTaskId(taskId);
        if (history != null) {
            cacheService.clearUserHistoryCache(history.getUserId());
            cacheService.clearTaskStatusCache(taskId);
            
            // 发布任务失败通知
            cacheService.publishTaskCompletion(taskId, "FAIL", "模型生成失败: " + errorMessage);
            
            // 发送WebSocket实时通知
            TaskNotificationEndpoint.sendTaskNotification(
                history.getUserId().toString(), 
                taskId, 
                "FAIL", 
                "任务失败: " + errorMessage
            );
        }
        
        log.error("模型生成任务失败: taskId={}, error={}", taskId, errorMessage);
    }
    
    @Override
    public ModelHistory findByTaskId(String taskId) {
        // 先尝试从缓存获取
        ModelHistoryVO cached = cacheService.getTaskStatusFromCache(taskId);
        if (cached != null) {
            ModelHistory history = new ModelHistory();
            BeanUtils.copyProperties(cached, history);
            return history;
        }
        
        // 缓存中没有，查询数据库
        ModelHistory history = modelHistoryMapper.findByTaskId(taskId);
        if (history != null) {
            // 缓存任务状态
            ModelHistoryVO vo = new ModelHistoryVO();
            BeanUtils.copyProperties(history, vo);
            cacheService.cacheTaskStatus(taskId, vo);
        }
        return history;
    }
    
    @Override
    public List<ModelHistoryVO> findByUserId(Long userId) {
        // 先尝试从缓存获取
        List<ModelHistoryVO> cached = cacheService.getUserHistoryFromCache(userId);
        if (cached != null) {
            return cached;
        }
        
        // 缓存中没有，查询数据库（只查询24小时内的记录）
        LocalDateTime twentyFourHoursAgo = LocalDateTime.now().minusHours(24);
        List<ModelHistory> histories = modelHistoryMapper.findByUserIdAndTimeRange(userId, twentyFourHoursAgo);
        
        List<ModelHistoryVO> result = histories.stream().map(history -> {
            ModelHistoryVO vo = new ModelHistoryVO();
            BeanUtils.copyProperties(history, vo);
            return vo;
        }).collect(Collectors.toList());
        
        // 缓存结果
        cacheService.cacheUserHistory(userId, result);
        return result;
    }
}
